import React, {CSSProperties} from "react";
import { Upload, Button, Modal, message,Row,Col} from 'antd';
import {RedoOutlined,UndoOutlined,SyncOutlined,
    ArrowLeftOutlined,
    ArrowRightOutlined,
    ArrowUpOutlined,
    ArrowDownOutlined,
    ColumnWidthOutlined,
    ColumnHeightOutlined}from '@ant-design/icons';
import Cropper from 'react-cropper';
import "cropperjs/dist/cropper.css"
import {
    VJsonComponent,
    VJsonComponentBase,
} from "../factory";
import _ from 'lodash'
import {toJS} from "mobx";
import {apply, YvanEventDispatch} from "..";
import * as Extend from '../extend'

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

export interface UploadCropperVJsonProp {
    /**
     * 是否可见
     */
    visible?: boolean
    style?: CSSProperties
    className?:string
}

export interface UploadCropperState {
    previewVisible:boolean,
    selectedImageFile:any,
    previewImage:any,
    width: any,
    height: any,
    pattern: any,
    fileList: any,
    editImageModalVisible: boolean,
    srcCropper: any,
    selectImgName: any,
    selectImgSize:any,
    selectImgSuffix:any,
    file:any,
    getData:any[],
    scaleLeft:boolean,
    scaleTop:boolean
}

@VJsonComponent({
    view: 'uploadCropper'
})
export default class UploadCropper extends VJsonComponentBase<UploadCropperVJsonProp, UploadCropperState> {
    static defaultProps: UploadCropperVJsonProp = {
        visible: true
    }
    cropper: any
    constructor(props: any) {
        super(props);

        _.defaults(
            props.vjson,
            UploadCropper.defaultProps
        )

        this.state={
            previewVisible:false,
            selectedImageFile:'',
            previewImage:'',
            width: props.vjson.width,
            height: props.vjson.height,
            pattern: props.vjson.pattern,
            fileList: props.vjson.fileList ? props.vjson.fileList : [],
            editImageModalVisible: false,
            srcCropper: '',
            selectImgName: '',
            selectImgSize:'',
            selectImgSuffix:'',
            file:'',
            getData:[],
            scaleLeft:false,
            scaleTop:false
        }
        
    }

    componentWillReceiveProps(nextProps) {
        if ('fileList' in nextProps) {
          this.setState({
            fileList: nextProps.fileList ? nextProps.fileList : [],
          });
        }
    }

    getFileList(){//获取组件图片列表
        return this.state.fileList
    }

    setFileList(fileList){//图片列表赋值
        this.setState({
            fileList:fileList
        })
    }

    // 图片Upload上传之前函数
    beforeUpload(file, fileList) {
        if(this.props.vjson.fileType){
            let _fileType=file.type.split('/')[1];
            if(this.props.vjson.fileType.indexOf(_fileType)<0){
                message.error('请上传格式为'+this.props.vjson.fileType+'的文件')
                return false
            }
        }
        const isLt10M = file.size / 1024 / 1024 < 5;
        if (!isLt10M) { //添加文件限制
            message.error({ content: '文件大小不能超过5M' });
            return false;
        }
        
        var reader = new FileReader();
        const image = new Image();
        //因为读取文件需要时间,所以要在回调函数中使用读取的结果
        reader.readAsDataURL(file); //开始读取文件
        reader.onload = (e) => {
            this.setState({
                srcCropper: reader.result, //cropper的图片路径
                selectImgName: file.name, //文件名称
                selectImgSize: (file.size / 1024 / 1024), //文件大小
                selectImgSuffix: file.type.split("/")[1], //文件类型
                editImageModalVisible: true, //打开控制裁剪弹窗的变量，为true即弹窗
                file:file
        })
        if (this.cropper) {
            this.cropper.replace(reader.result);
        }
        }
        return false;
    }

    //将base64码转化成blob格式
    convertBase64UrlToBlob(base64Data) {
        var byteString;
        if (base64Data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(base64Data.split(',')[1]);
        } else {
        byteString = unescape(base64Data.split(',')[1]);
        }
        var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ia], { type: this.state.selectImgSuffix });
    }
    
    //将base64码转化为FILE格式
    dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
        while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    }

    onCropperInit=(cropper:any) => { this.cropper = cropper }
    _ready(){
        this.cropper.setData({
            width:this.props.vjson.width?this.props.vjson.width:800,
            height:this.props.vjson.height?this.props.vjson.height:800,
        });
    }
    private rotateClockwise(){//顺时针旋转
        this.cropper.rotate(90);
    }
    private rotate(){//逆时针旋转
        this.cropper.rotate(-90);   
    }
    private reset(){//重置
        this.cropper.reset();
        this.cropper.setData({
            width:this.props.vjson.width?this.props.vjson.width:500,
            height: this.props.vjson.height?this.props.vjson.height:500,
        });
    }
    private moveLeft(){
        this.cropper.move(-5, 0);
    }
    private moveRight(){
        this.cropper.move(5, 0);
    }
    private moveTop(){
        this.cropper.move(0, 5);
    }
    private moveDown(){
        this.cropper.move(0, -5);
    }
    private scaleLeft(){//左右翻转
        if(!this.state.scaleLeft){
            this.cropper.scale(-1, 1);
            this.setState({
                scaleLeft:true
            })
        }else{
            this.cropper.scale(1, 1);
            this.setState({
                scaleLeft:false
            })
        }
    }
    private scaleTop(){//上下翻转
        if(!this.state.scaleTop){
            this.cropper.scale(1, -1);
            this.setState({
                scaleLeft:true
            })
        }else{
            this.cropper.scale(1, 1);
            this.setState({
                scaleTop:false
            })
        }
    }

    saveImg() {//裁剪保存
        let imageArry = this.state.fileList.slice();
        let data={}
        data[this.props.vjson.name]=this.dataURLtoFile(this.cropper.getCroppedCanvas().toDataURL(), this.state.selectImgName)
        console.log(this.cropper.getCroppedCanvas())
        // @ts-ignore
        Extend.ajax.func({
            method: 'post-file',
            url: this.props.vjson.url,
            data: data
        }).then(res => {
            if(res.success){
                this.setState({
                    fileList: imageArry,
                    editImageModalVisible: false, //打开控制裁剪弹窗的变量，为true即弹窗
                })
                imageArry.push({
                    uid: Math.random() * 100000,
                    name: this.state.selectImgName,
                    status: 'done',
                    url:this.props.vjson.previewUrl+res.data.mdm_server_name,
                    server_url:res.data.mdm_server_url,
                    upload: true,
                    serverName:res.data.mdm_server_name
                })
            }
        }).catch(e=>{
            message.error('上传失败')
        })
    }

    handleCancel(){//取消裁剪
        this.setState({
            editImageModalVisible: false,
        });
    }

    handlePreview= async file=>{//查看
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
          }
          this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
          });
    }

    handleSeeCancel(){//取消查看
        this.setState({
            previewVisible: false
        });
    }

    handleRemove(file) {//删除
        this.setState((state) => {
            const index = state.fileList.indexOf(file);
            const newFileList = state.fileList.slice();
            newFileList.splice(index, 1);
            return {
                fileList: newFileList,
            };
        });
    }

    render() {
        if (!this.props.vjson.visible) {
            return null
        }
        const botton = this.state.pattern == 2 ?
        <div>
            <div className="ant-upload-text">Upload</div>
        </div> :<span>选择上传</span>
        return (
            <div>
                <Upload
                    name={this.props.vjson.name}
                    action={this.props.vjson.url}
                    listType="picture-card"
                    beforeUpload={this.beforeUpload.bind(this)}
                    onRemove={this.handleRemove.bind(this)}
                    fileList={this.state.fileList}
                    onPreview={this.handlePreview}
                    //onChange={this.onChange}
                >
                    {botton}
                </Upload>
                <Modal title="图片裁剪"
                    key="cropper_img_icon_key"
                    visible={this.state.editImageModalVisible}
                    width="100%"
                    onCancel={this.handleCancel.bind(this)} onOk={this.saveImg.bind(this)}
                    >
                        <div className="cropper">
                            <div className="cropper-content">
                            <Cropper
                                src={this.state.srcCropper} //图片路径，即是base64的值，在Upload上传的时候获取到的
                                onInitialized={this.onCropperInit.bind(this)}
                                preview=".uploadCrop"
                                viewMode={1} //定义cropper的视图模式
                                zoomable={true} //是否允许放大图像
                                movable={true}
                                guides={true} //显示在裁剪框上方的虚线
                                background={false} //是否显示背景的马赛克
                                rotatable={true} //是否旋转
                                style={{ height: '100%', width: '100%' }}
                                cropBoxResizable={true}
                                cropBoxMovable={true}
                                dragMode="move"
                                center={true}
                                ready={this._ready.bind(this)}
                                />
                            </div>
                            <div className="cropper-mode">
                                <span className="cropper-btn" onClick={this.moveLeft.bind(this)} title="左移"><ArrowLeftOutlined /></span>
                                <span className="cropper-btn" onClick={this.moveRight.bind(this)} title="右移"><ArrowRightOutlined /></span>
                                <span className="cropper-btn" onClick={this.moveTop.bind(this)} title="上移"><ArrowUpOutlined /></span>
                                <span className="cropper-btn" onClick={this.moveDown.bind(this)} title="下移"><ArrowDownOutlined /></span>
                                <span className="cropper-btn" onClick={this.rotateClockwise.bind(this)} title="顺时针旋转"><RedoOutlined /></span>
                                <span className="cropper-btn" onClick={this.rotate.bind(this)} title="逆时针旋转"><UndoOutlined /></span>
                                <span className="cropper-btn" onClick={this.scaleLeft.bind(this)} title="左右翻转"><ColumnWidthOutlined /></span>
                                <span className="cropper-btn" onClick={this.scaleTop.bind(this)} title="上下翻转"><ColumnHeightOutlined /></span>
                                <span className="cropper-btn" onClick={this.reset.bind(this)} title="重置"><SyncOutlined /></span>
                            </div>
                        </div>
                </Modal>
                <Modal visible={this.state.previewVisible} title='查看图片' footer={null} onCancel={this.handleSeeCancel.bind(this)}
                    width={800}
                    >
                    <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal>
            </div>
        )
    }
}
